<template>
	<t-tabs class="bg-white h-full w-full" :defaultValue="1">
		<t-tab-panel :value="1" label="待提交" destroyOnHide>
			<div class="p-4">
				<div class="flex justify-between mt-4 mb-4">
					<div class="flex">
						<t-button class="mr-4" @click="openAddUserDialog()">添加</t-button>
						<t-button theme="danger" @click="deleteData()">删除</t-button>
					</div>
					<div class="flex">
						<t-button class="mr-4" variant="outline" @click="Reset()">重置</t-button>
						<t-button class="mr-4" @click="save()">保存</t-button>
						<t-button theme="success" @click="submit()">提交</t-button>
					</div>
				</div>
				<div v-for="(item, index) in data[0]" :key="index" class="mb-8">
					<p class="text-gray-900 text-lg">{{item[0].s_date.slice(0,4)}}年{{item[0].s_date.slice(5)}}月工资表</p>
					<t-table
					:bordered="true"
					rowKey="s_id"
					:columns="columnsNo"
					:data="item"
					:selected-row-keys="selectedRowKeys"
					@select-change="rehandleSelectChange"
					:pagination="{ defaultCurrent: 1, defaultPageSize: 20, total: item.length }"
					class="mt-2"
					>
						<template #s_award="{row}">
							<t-input v-model="row.s_award"></t-input>
						</template>
						<template #s_fine="{row}">
							<t-input v-model="row.s_fine"></t-input>
						</template>
						<template #s_endowent_insurance="{row}">
							<t-input v-model="row.s_endowent_insurance"></t-input>
						</template>
						<template #s_medical_insurance="{row}">
							<t-input v-model="row.s_medical_insurance"></t-input>
						</template>
						<template #s_unemployment_insurance="{row}">
							<t-input v-model="row.s_unemployment_insurance"></t-input>
						</template>
						<template #s_employment_insurance="{row}">
							<t-input v-model="row.s_employment_insurance"></t-input>
						</template>
						<template #s_maternity_insurance="{row}">
							<t-input v-model="row.s_maternity_insurance"></t-input>
						</template>
						<template #s_remark="{row}">
							<t-input v-model="row.s_remark" placeholder="请输入备注"></t-input>
						</template>
					</t-table>
				</div>
				<div class="text-gray-400 mb-2">
					<p>工资计算公式<span class="text-red-800"> *</span></p>
					<p>实际应发 = （岗位工资 / 满勤天数 * 实际出勤天数）+ 奖金 +（岗位工资 / 满勤天数 / 8 * 加班时数）- 扣款 - 五险</p>
				</div>
			</div>
			<!-- 添加成员弹窗 -->
			<t-dialog
			header="添加人员"
			:visible.sync="visible"
			:onConfirm="onConfirmAnother"
			:confirmBtn="loading"
			>
				<t-cascader 
				v-model="cascaderValue" 
				:options="optionsT" 
				multiple
				clearable
				class="mt-2 mb-8"
				placeholder="请选择想要添加的人员"
				/>
			</t-dialog>
		</t-tab-panel>
		<t-tab-panel :value="2" label="已提交" class="p-4">
			<div v-for="(item, index) in data[1]" :key="index" class="mb-8">
				<p class="text-gray-900 text-lg mb-4">{{item[0].s_date.slice(0,4)}}年{{item[0].s_date.slice(5)}}月工资表</p>
				<t-table
				:bordered="true"
				rowKey="s_id"
				:columns="columnsYes"
				:data="item"
				:pagination="{ defaultCurrent: 1, defaultPageSize: 20, total: item.length }"
				></t-table>
			</div>
		</t-tab-panel>
	</t-tabs>
</template>

<script>
	import loot from '@/unit/loot'
	
	const getColumsNo = (isFixedColumn) => [
		{ colKey: 'row-select', type: 'multiple', fixed: 'left', attrs:{['style']: "background-color: #f7f7f7"}},
		{ colKey: 's_user_name', title: '员工昵称', fixed: 'left', width: 120, attrs:{['style']: "background-color: #f7f7f7"}},
		{ colKey: 's_department_name', title: '所属部门', width: 120},
		{ colKey: 's_position_name', title: '岗位职称', width: 120 },
		{ colKey: 's_shoud_salary', title: '满勤天数', width: 120 },
		{ colKey: 's_office_day', title: '实际出勤天数', width: 140 },
		{ colKey: 's_rest_day', title: '调休', width: 80 },
		{ colKey: 's_overtime_day', title: '加班', width: 80 },
		{ colKey: 's_post_salary', title: '岗位工资', width: 120 },
		{ colKey: 's_award', title: '绩效奖励', width: 120 },
		{ colKey: 's_fine', title: '扣款', width: 120 },
		{ colKey: 's_endowent_insurance', title: '养老保险', width: 120 },
		{ colKey: 's_medical_insurance', title: '医疗保险', width: 120 },
		{ colKey: 's_unemployment_insurance', title: '失业保险', width: 120 },
		{ colKey: 's_employment_insurance', title: '工伤保险', width: 120 },
		{ colKey: 's_maternity_insurance', title: '生育保险', width: 120 },
		{ colKey: 's_practical_salary', title: '实际应发', width: 160 },
		{ colKey: 's_remark', title: '备注', width: 200 }
	]
	
	const getColumsYes = (isFixedColumn) => [
		{ colKey: 's_user_name', title: '员工昵称', fixed: 'left', width: 120, attrs:{['style']: "background-color: #f7f7f7"}},
		{ colKey: 's_department_name', title: '所属部门', width: 120},
		{ colKey: 's_position_name', title: '岗位职称', width: 120 },
		{ colKey: 's_shoud_salary', title: '满勤天数', width: 120 },
		{ colKey: 's_office_day', title: '实际出勤天数', width: 140 },
		{ colKey: 's_rest_day', title: '调休', width: 80 },
		{ colKey: 's_overtime_day', title: '加班', width: 80 },
		{ colKey: 's_post_salary', title: '岗位工资', width: 120 },
		{ colKey: 's_award', title: '绩效奖励', width: 120 },
		{ colKey: 's_fine', title: '扣款', width: 120 },
		{ colKey: 's_endowent_insurance', title: '养老保险', width: 120 },
		{ colKey: 's_medical_insurance', title: '医疗保险', width: 120 },
		{ colKey: 's_unemployment_insurance', title: '失业保险', width: 120 },
		{ colKey: 's_employment_insurance', title: '工伤保险', width: 120 },
		{ colKey: 's_maternity_insurance', title: '生育保险', width: 120 },
		{ colKey: 's_practical_salary', title: '实际应发', width: 160 },
		{ colKey: 's_remark', title: '备注', width: 200 }
	]
	
	export default {
		name: 'Salary',
		inject: ['reload'],
		data(){
			return {
				data: [[],[]],
				fixedColumn: false,
				selectedRowKeys: [],
				mydialog: null,
				visible: false,
				loading: {},
				cascaderValue: []
			}
		},
		computed: {
			// 未提交表头配置
			columnsNo(){
				return getColumsNo(this.fixedColumn)
			},
			// 已提交表头配置
			columnsYes(){
				return getColumsYes(this.fixedColumn)
			},
			// 配置项
			optionsT(){
				return this.$store.state.salary.userList
			}
		},
		watch: {
			// 监听data，自动计算实际工资
			data: {
				deep:true,
				handler(){
					clearTimeout(this.timeout);
					this.timeout = setTimeout(() => {
						for(let i = 0; i < this.data[0].length ; i++){
							this.data[0][i].map(item => {
								for(let i in item){
									if( item[i] === '' && Object.keys(item) !== 's_remark' ){ item[i] = 0 }
								}
								item.s_practical_salary = loot.keepTwoDecimal((item.s_post_salary / item.s_shoud_salary * item.s_office_day) + parseInt(item.s_award) + (item.s_post_salary / item.s_shoud_salary / 8 * item.s_overtime_day) - item.s_fine - item.s_endowent_insurance - item.s_medical_insurance - item.s_unemployment_insurance - item.s_maternity_insurance - item.s_employment_insurance)
							})
						}
					}, 500);
				}
			},
		},
		methods: {
			// 重置
			Reset(){
				this.reload()
			},
			// 确认添加人员
			onConfirmAnother(){
				this.loading = {
					content: '添加中...',
					theme: 'primary',
					loading: true
				}
				let arr = []
				this.cascaderValue.map(item => {
					arr.push(loot.getCaption(item, 1))
				})
				let ids = arr.concat(this.$route.query.ids)
				loot.unique(ids)
				const query=JSON.parse(JSON.stringify(this.$route.query))
				query.IsBinding=true
				this.$router.push({ path: this.$route.path, query: {ids} })
				this.reload()
				this.$message.success('添加成功')
			},
			// 打开添加人员弹窗
			openAddUserDialog(){
				this.visible = true
			},
			// 删除数据
			deleteData(){
				if(this.selectedRowKeys.length === 0) return this.$message.error('您还没有选择任何一条数据')
				// 将s_id替换为s_user_id
				let arr = []
				this.selectedRowKeys.map(selectItem => {
					this.data[0].map(dataList => {
						dataList.map(dataItem => {
							if(selectItem == dataItem.s_id){
								arr.push(dataItem.s_user_id)
							}
						})
					})
				})
				// 去掉里面重复的数组
				loot.unique(arr)
				let newQuearyIds = this.$route.query.ids
				for(let i = 0 ; i < newQuearyIds.length ; i++){
					for(let j = 0 ; j < arr.length ; j++){
						if(arr[j] == newQuearyIds[i]){
							newQuearyIds.splice(i, 1)
						}
					}
				}
				const query=JSON.parse(JSON.stringify(this.$route.query))
				query.IsBinding=true
				this.$router.push({ path: this.$route.path, query: {ids: newQuearyIds} })
				this.reload()
				this.$message.success('删除成功')
			},
			// 处理提交的数据
			processingData(){
				let arr = []
				let index = 0
				for(let i = 0 ; i < this.data[0].length ; i++){
					this.data[0][i].map(item => {
						for(let j = 0 ; j < this.selectedRowKeys.length ; j++){
							if(item.s_id == this.selectedRowKeys[j]){
								arr[index] = item
								index ++
							}
						}
					})
				}
				index = 0
				arr.map(item => {
					delete item.s_user_name
					delete item.s_department_name
					delete item.s_position_name
					delete item.s_shoud_salary
				})
				return arr
			},
			// 提交
			submit(){
				if(this.selectedRowKeys.length === 0) return this.$message.error('您还没有选择任何一条数据')
				if (this.mydialog) {
					this.mydialog.show();
					return;
				}
				this.mydialog = this.$dialog({
					header: '提示',
					body: '是否确认提交，提交成功后只有审核时才可继续编辑',
					onConfirm: ({ e }) => {
						let arr = this.processingData()
						this.$store.dispatch('salary/submitSalary', arr).then(res => {
							if(res.status === 0){
								this.$message.success(res.message)
								this.reload()
							} else {
								this.$message.error(res.message)
							}
						})
						this.mydialog.hide();
					},
				});
			},
			// 保存
			save(){
				if(this.selectedRowKeys.length === 0) return this.$message.error('您还没有选择任何一条数据')
				let arr = this.processingData()
				this.$store.dispatch('salary/saveSalary', arr).then(res => {
					if(res.status === 0){
						this.$message.success(res.message)
						this.reload()
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 表格复选框
			rehandleSelectChange(value, { selectedRowData }){
				this.selectedRowKeys = value
			},
			// 获取表格基本信息
			getUserSalary(arr){
				let ids = ''
				for(let i = 0; i < arr.length; i++){
					ids = ids + '@' + arr[i]
				}
				ids = ids.substr(1)
				this.$store.dispatch('salary/getAllSalary', ids).then(res => {
					if (res.status === 0){
						// 计算应上班天数
						res.data.map(item => {
							item.s_shoud_salary = item.s_all_day - item.s_rest_all_day
						})
						// 对res.data进行分组
						res.data.map(item => {
							if (item.s_audit_state === 0){
								this.data[0].push(item)
							} else {
								this.data[1].push(item)
							}
						})
						const groupBy = (array, f) => {
							let groups = {}
							array.forEach( o => {
								let group = JSON.stringify(f(o))
								groups[group] = groups[group] || []
								groups[group].push(o)
							})
							return Object.keys(groups).map((group) => {
								return groups[group]
							})
						}
						this.data[0] = groupBy(this.data[0], (item) => {return item.s_date})
						this.data[1] = groupBy(this.data[1], (item) => {return item.s_date})
					} else {
						this.$message.error(res.message)
					}
				})
			}
		},
		created(){
			this.$store.dispatch('salary/getUserList')
			
		},
		mounted(){
			this.getUserSalary(this.$route.query.ids)
		}
	}
</script>

<style scoped lang="less">
	.bg-color{
		background-color: aqua !important;
	}
</style>